package com.heima.wemadia.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.heima.file.MinIOTemplate;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmMaterialDto;
import com.heima.model.wemedia.entity.WmMaterial;
import com.heima.model.wemedia.entity.WmNewsMaterial;
import com.heima.wemadia.dao.WmMaterialDao;
import com.heima.wemadia.dao.WmNewsMaterialDao;
import com.heima.wemadia.service.WmMaterialService;
import com.heima.wemadia.utils.WmThreadLocalUtil;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 自媒体素材表(WmMaterial)表服务实现类
 *
 * @author makejava
 * @since 2022-04-10 16:58:20
 */
@Service("wmMaterialService")
public class WmMaterialServiceImpl implements WmMaterialService {
    @Resource
    private WmMaterialDao wmMaterialDao;
    @Resource
    private MinIOTemplate minIOTemplate;
    @Resource
    private WmNewsMaterialDao wmNewsMaterialDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public WmMaterial queryById(Long id) {
        return this.wmMaterialDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param wmMaterial  筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<WmMaterial> queryByPage(WmMaterial wmMaterial, PageRequest pageRequest) {
        long total = this.wmMaterialDao.count(wmMaterial);
        return new PageImpl<>(this.wmMaterialDao.queryAllByLimit(wmMaterial, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param wmMaterial 实例对象
     * @return 实例对象
     */
    @Override
    public WmMaterial insert(WmMaterial wmMaterial) {
        this.wmMaterialDao.insert(wmMaterial);
        return wmMaterial;
    }

    /**
     * 修改数据
     *
     * @param wmMaterial 实例对象
     * @return 实例对象
     */
    @Override
    public WmMaterial update(WmMaterial wmMaterial) {
        this.wmMaterialDao.update(wmMaterial);
        return this.queryById(wmMaterial.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.wmMaterialDao.deleteById(id) > 0;
    }

    @Override
    public ResponseResult uploadPic(MultipartFile multipartFile) {
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        String filename = multipartFile.getOriginalFilename();
        filename = UUID.randomUUID().toString().replace("-", "") + filename.substring(filename.lastIndexOf("."));

        try {
            String url = minIOTemplate.uploadImgFile("", filename, multipartFile.getInputStream());
            //3. 保存素材数据到数据库
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
            wmMaterial.setUrl(url);
            wmMaterial.setType(0);
            wmMaterial.setIsCollection(0);
            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setUpdatedTime(new Date());

            wmMaterialDao.insert(wmMaterial);
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "上传失败");
        }
    }

    @Override
    public ResponseResult list(WmMaterialDto dto) {

        dto.checkParam();

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1 ) {
            wmMaterial.setIsCollection(dto.getIsCollection());
        }

        PageHelper.startPage(dto.getPage(), dto.getSize());
        com.github.pagehelper.Page<WmMaterial> wmMaterials = wmMaterialDao.queryAll(wmMaterial);
        ResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(), (int) wmMaterials.getTotal());
      //  ResponseResult result = new PageResponseResult(wmMaterials.getPageNum(),wmMaterials.getPageSize(), (int) wmMaterials.getTotal());

        result.setData(wmMaterials);

        return result;
    }

    @Override
    public ResponseResult deleteByImageId(Long imageId) {
        if (imageId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        List<WmNewsMaterial> list=wmNewsMaterialDao.selectByMaterialId(imageId);
        if(!CollectionUtil.isEmpty(list)){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"用文章引用该素材,无法删除");
        }
        wmMaterialDao.deleteById(imageId);
        return ResponseResult.okResult("操作成功");
    }

    @Override
    public ResponseResult collectImages(Long imageId) {
       return getResponseResult(imageId,1);
    }

    @Override
    public ResponseResult cancelCollect(Long imageId) {
        return getResponseResult(imageId,0);
    }

    private ResponseResult getResponseResult(Long imageId,Integer status) {
        if (imageId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(imageId);
        wmMaterial.setIsCollection(status);
        wmMaterialDao.update(wmMaterial);
        return ResponseResult.okResult("操作成功");
    }
}
